/* 
 * AUTHOR: Kevin Lam
 */

package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.SectionInformationObject;
import com.apps.services.CourseSummaryService;
import com.apps.ubc.cc.model.LatLongModel;

public class SummaryController extends HttpServlet{
	
	CourseSummaryService cs = new CourseSummaryService();
	AccountInformationDatastore d = new AccountInformationDatastore();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		String email = req.getParameter("email");
		Cookie[] cookies = req.getCookies();
		String user = null;
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals("user"))
				user = cookies[i].getValue();
		}
		String xmlout = "<response>\n";
		if(user != null && (d.checkSubscriptionExists(email, user) || email.equals(user))) {
			List<SectionInformationObject> siol = d.getWorklistAsSIO(email);	
			String action = req.getParameter("action");
			if(action.equals("getstartend")) {
				String[] startEnd = cs.getStartEnd(siol);
				xmlout += "\t<start>"+startEnd[0]+"</start>\n";
				xmlout += "\t<end>"+startEnd[1]+"</end>\n";
			}
			else if(action.equals("getsummary")){
				String summary = cs.getSummarySchedule(siol);
				xmlout += "\t<summary>"+summary+"</summary>\n";
			}
			else if(action.equals("getwaypoints")){
				String term = req.getParameter("term");
				List<LatLongModel> llml = cs.getLatLongByTerm(siol, term);
				for(Iterator<LatLongModel> i = llml.iterator();i.hasNext();){
					xmlout += "\t<waypoint>\n";
					LatLongModel llm = i.next();
					xmlout += "\t\t<lat>"+llm.getLatitude()+"</lat>\n";
					xmlout += "\t\t<long>"+llm.getLongitude()+"</long>\n";
					xmlout += "\t</waypoint>\n";
				}
			}
			
			xmlout += "</response>";
			
			try {
				resp.setContentType("text/xml; charset=UTF-8");
				resp.getWriter().write(xmlout);
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		}
	
	}

}
